const fs = require('fs')
const os = require('os')
const path = require('path')
const ftp = require('promise-ftp')
const schedule = require('node-schedule')
const electron = require('electron')
const { app, Menu, BrowserWindow, ipcMain, Tray, dialog, Notification } = require('electron')
const { foperator } = require('./js/folder.operation')
const moment = require('moment')
const url = require('url')
require('events').EventEmitter.prototype._maxListeners = 0;


const client = new ftp();

let mainWindow = null

//托盘对象
let appTray = null

const assets = path.join(__dirname, 'icons')
const appIcon = path.join(assets, 'win')

// 系统托盘右键菜单
// 退出 - 因为程序设定关闭为最小化，所以调用两次关闭，防止最大化时一次不能关闭的情况
var trayMenuTemplate = [
  {
    label: '退出',
    click: (e) => {
      app.quit()
      app.quit()
      appTray.destroy()
    }
  }
];
//图标的上下文菜单
const contextMenu = Menu.buildFromTemplate(trayMenuTemplate)

function createWindow() {
  Menu.setApplicationMenu(null)
  // 创建浏览器窗口
  const size = electron.screen.getPrimaryDisplay().size
  mainWindow = new BrowserWindow({
    icon: path.join(appIcon, "app.ico"),
    frame: false,
    width: 1500,
    height: 860,
    webPreferences: {
      nodeIntegration: true
    },
    show: false
  })
  // win.maximize();

  // 加载index.html文件
  // win.loadFile('index.html')
  mainWindow.loadURL(`file://${__dirname}/index.html?v=${new Date().getTime()}`)
  // mainWindow.webContents.openDevTools()

  mainWindow.on('close', (e) => {
    app.quit()
    app.quit()
    appTray.destroy()
  })

  mainWindow.once('ready-to-show', () => {
    mainWindow.show()
  })
}

// 禁用本地缓存，一定要使用在app.ready之前
app.commandLine.appendSwitch("--disable-http-cache")

app.disableHardwareAcceleration()

app.setUserTasks([
  {
    program: process.execPath,
    arguments: '--new-window',
    iconPath: process.execPath,
    iconIndex: 0,
    title: 'FTP SCHEDULE TRANS',
    description: 'FTP SCHEDULE TRANS'
  }
])

let notificationInfo = null

app.on('ready', () => {
  createWindow()

  notificationInfo = new Notification({
    title: 'FTP 信息',
    body: 'FTP服务器已链接'
  })

  appTray = new Tray(path.join(appIcon, 'app.ico')) //app.ico是app目录下的ico文件

  //设置此托盘图标的悬停提示内容
  appTray.setToolTip('FTP 定时上传工具')

  //设置此图标的上下文菜单
  appTray.setContextMenu(contextMenu)

  appTray.on('double-click', () => {
    mainWindow.show()
    mainWindow.setSkipTaskbar(false)
  })

})

ipcMain.on('close-app', function () {
  mainWindow.minimize();
})

ipcMain.on('select-local-folder', (event) => {
  dialog.showOpenDialog(mainWindow, {
    properties: ['openDirectory']
  }).then(result => {
    if (result.canceled) {
      console.log('Dialog was canceled')
    } else {
      const file = result.filePaths[0]
      mainWindow.webContents.send('fill-folder-address', file)
    }
  }).catch(err => {
    console.log(err)
  })
})

ipcMain.on('start-ftp', (e, args) => {
  ftpInfo = args
  if (client.getConnectionStatus() != 'connected') {
    mainWindow.webContents.send('record-info', 'info', 'FTP地址:' + args.url + 'FTP端口:' + args.port)
    mainWindow.webContents.send('record-info', 'info', 'FTP账号:' + args.name)
    mainWindow.webContents.send('record-info', 'warning', '正在链接FTP服务器......')
    client.connect({
      host: args.url,
      port: args.port,
      user: args.name,
      password: args.pwd,
      keepalive: 10000
    }).then(function (serverMessage) {
      // 状态分为not yet connected/connecting/connected/logging out/disconnecting/disconnected/reconnecting
      let timerCount = 0
      let contnectTimer = setInterval(() => {
        mainWindow.webContents.send('record-info', 'warning', '正在链接FTP服务器......')
        if (client.getConnectionStatus() == 'connected') {
          mainWindow.webContents.send('record-info', 'success', serverMessage)
          mainWindow.webContents.send('record-info', 'success', '成功链接FTP服务器。')
          clearInterval(contnectTimer)
        } else {
          ++timerCount
          if (timerCount < 6) {
            clearInterval(contnectTimer)
            mainWindow.webContents.send('record-info', 'disconnect', '未链接FTP服务器，请检查网络及配置信息。')
          }
        }
      }, 2000)

    }).catch(function (a) {
      mainWindow.webContents.send('record-info', 'disconnect', '未链接FTP服务器，请检查网络及FTP配置信息。')
      console.info(a)
    })
  } else {
    mainWindow.webContents.send('record-info', 'success', '已链接FTP服务器。')
  }

})

function uploadAction(fromDir) {

  let fileDirectory = fromDir
  if (fs.existsSync(fileDirectory)) {

    let paths = foperator.getPaths(fileDirectory)
   
    let pathLen = paths.length

    if (!pathLen) {
      mainWindow.webContents.send('record-info', 'warning', ' 执行定时任务，所选的本地文件夹暂时没有文件。')
      return
    }

    foperator.copy(fileDirectory, fileDirectory + '_备份_' + pathLen + '_' + moment().format('YYYY_MM_DD_hh_mm_ss'));
    mainWindow.webContents.send('record-info', 'success', ' 备份 ' + pathLen + ' 文件成功。')

    let dirLen = ~~fileDirectory.length
    
    for (var i = 0; i < pathLen; i++) {
      let srcPath = paths[i]
      let destPathStr = srcPath.substr(dirLen)
      let destPath =  destPathStr.replace(/\\/g, '/')

      let dirPath = path.dirname(destPath)
      let filename = path.basename(destPath)

      if (dirPath) {
        // 判断文件夹是否存在
        client.cwd(dirPath)
        .then(function (cwdDir) {
          client.put(srcPath, destPath)
          .then(function () {
            mainWindow.webContents.send('record-info', 'success', ' upload ' + srcPath)
          })
          .then(function(){
            fs.unlinkSync(srcPath)
          })
          .then(function(){
            mainWindow.webContents.send('record-info', 'default', ' delete ' + srcPath)
          })
          .catch(function(err){
            mainWindow.webContents.send('record-info', 'danger', srcPath + '上传FTP服务器失败。')
          })
        }).catch(function(err){
          mainWindow.webContents.send('record-info', 'warning', 
            '无法上传[' + filename + ']文件<br/>FTP服务器没有[' + dirPath + ']文件夹<br>或检查网络'
          )
        })
      }
    }
  }
}



let taskOne
ipcMain.on('task-start', (e, args) => {
  if (!args.folder) {
    notificationInfo.body = '请选择文件夹'
    notificationInfo.show()
    mainWindow.webContents.send('record-info', 'success', '请选择文件夹')
  } else {
    mainWindow.webContents.send('record-info', 'success', '开始定时任务')
    taskOne = schedule.scheduleJob(args.schedule, () => {
      if (client.getConnectionStatus() == 'connected') {
        uploadAction(args.folder)
      } else {
        client.reconnect()
        uploadAction(args.folder)
      }
    })
  }
})

ipcMain.on('cancel-ftp', (event) => {
  if (client.getConnectionStatus() == 'connected') {
    client.end()
    mainWindow.webContents.send('record-info', 'close', '关闭FTP服务链接')
    console.info(client.getConnectionStatus())
  } else {
    mainWindow.webContents.send('record-info', 'disconnect', '未链接FTP服务器')
  }

  if (taskOne) {
    taskOne.cancel()
    mainWindow.webContents.send('record-info', 'close', '关闭定时任务')
    taskOne = null
  }
})

ipcMain.on('cancel-task', (e) => {
  if (taskOne) {
    taskOne.cancel()
    mainWindow.webContents.send('record-info', 'close', '关闭定时任务')
    taskOne = null
  } else {
    mainWindow.webContents.send('record-info', 'notask', '未有定时执行任务')
  }
})


